package com.dycn.config;


import com.dycn.dao.*;
import com.dycn.exception.GlobalException;
import com.dycn.model.SysRoleResource;
import com.dycn.model.SysUser;
import com.dycn.model.SysUserRole;
import com.dycn.util.AppResultData;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;


    @Autowired
    SysResourceMapper sysResourceMapper;
     @Autowired
     SysRoleResourceMapper sysRoleResourceMapper;
      @Autowired
      SysUserRoleMapper sysUserRoleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        String username = (String)principals.getPrimaryPrincipal();
        SysUser sysUser = sysUserMapper.findByUsername(username);
//        Set<String> roles = sysRoleMapper.listRoleBySysUserId(sysUser.getId());
//        authorizationInfo.setRoles(roles);
//
       //Set<String> permissions = sysResourceMapper.getResources(sysUser.getId());

        SysUserRole sysUserRole=sysUserRoleMapper.findByUserId(sysUser.getId());
       List<SysRoleResource> sysRoleResourceList=sysRoleResourceMapper.findByRoleId(sysUserRole.getRoleId());
        Set<String> preList=new HashSet<>();
        for (SysRoleResource sysRoleResource:sysRoleResourceList){
            preList.add(sysRoleResource.getResourceCode());
        }

       authorizationInfo.setStringPermissions(preList);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String username = userToken.getUsername();
        SysUser sysUser = sysUserMapper.findByUsername(username);
        if(null==sysUser){
            throw  new GlobalException(AppResultData.errorMessage("用户名不存在"));
        }
        return new SimpleAuthenticationInfo(sysUser.getUsername(),sysUser.getPassword(),this.getClass().getName());
    }
}
